/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package ImageProcessingGUI;

import com.azon.ip.utils.ImageHelper;
import com.azon.ip.utils.ImageReader;
import com.azon.ip.utils.ImageWriter;
import com.azon.isip.detection.face.FaceDetection;
import com.azon.left.hand.WetLeftHand;
import com.isip.chaincode.ChainCode;
import com.isip.edgeDetection.*;
import com.isip.thining.ZhangSuen;
import com.isip.thining.model.ThinModel;
import com.isip.transformation.*;
import com.isip.transformation.difference.DifferenceFunction;
import com.isip.transformation.difference.MatrixTransformation;
import com.isip.transformation.difference.SimpleDifference;
import static java.awt.Component.CENTER_ALIGNMENT;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 *
 * @author Mahdan Ahmad F A
 */
public class CobaGUI extends javax.swing.JFrame {
    
    ChainCode[] models;
    ChainCode[] statisticModel;
    
    /**
     * Creates new form CobaGUI
     */
    public CobaGUI() {
        models = ChainCode.LoadModel();
        try {
            statisticModel = ChainCode.LoadModel("./image/model_statistik_1.txt");
        } catch (FileNotFoundException ex) {
            Logger.getLogger(CobaGUI.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(CobaGUI.class.getName()).log(Level.SEVERE, null, ex);
        }
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton2 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        jComboBox1 = new javax.swing.JComboBox();
        jButton1 = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Pengolahan Citra by Ahmad Fauzan");
        setBackground(new java.awt.Color(204, 204, 204));
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setFocusable(false);
        setName("Image Processing"); // NOI18N

        jButton2.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N
        jButton2.setText("Choose File");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N
        jLabel2.setText("Original Image");

        jLabel3.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N
        jLabel3.setText("Processed Image");

        jScrollPane1.setBackground(new java.awt.Color(153, 153, 0));
        jScrollPane1.setForeground(new java.awt.Color(153, 0, 0));
        jScrollPane1.setDoubleBuffered(true);

        jScrollPane2.setBackground(new java.awt.Color(255, 255, 255));

        jComboBox1.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N
        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Linear Transformation", "NineN Transformation", "LookUpTable Transformation", "edge 0 :  Difference Function", "edge 0 : Simple Difference", "edge 1 : FreiChen", "edge 1 : Kirsch", "edge 1 : Prewitt", "edge 1 : Robert", "edge 1 : Sobel", "edge 2 : FreiChen", "edge 2 : Prewitt", "edge 2 : Robert", "edge 2 : Sobel", "Check object using chain code", "Check Number (1)", "Check Number (2)", "Predict Number (Statistic Model - Chaincodes)", "Face Detection", "Scale --" }));
        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        jButton1.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N
        jButton1.setText("Execute");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel5.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N
        jLabel5.setText("Load Image :");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addGap(1, 1, 1)
                        .addComponent(jButton2))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 448, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton1))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 466, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(39, 39, 39)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1)
                    .addComponent(jLabel5))
                .addGap(21, 21, 21)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 477, Short.MAX_VALUE)
                    .addComponent(jScrollPane1))
                .addGap(15, 15, 15))
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        String[] suffices = ImageIO.getReaderFileSuffixes();
        
        //String  pathname = System.getProperty("user.home") + System.getProperty("file.separator")+ "Pictures";
        //File    path     = new File(pathname);
        
        JFileChooser openFile = new JFileChooser("./image");
        
        FileFilter filter = new FileNameExtensionFilter("Image File", suffices);
        openFile.setFileFilter(filter);
        //openFile.setCurrentDirectory(path);
        
        if (openFile.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            filepath = openFile.getSelectedFile().getAbsolutePath();
            
            ImageIcon   image = new ImageIcon(filepath);
            JLabel      label = new JLabel(image);
            
            jScrollPane2.setViewportView(label);
            jScrollPane2.setVisible(true);
            
        }
        
        
            

    }//GEN-LAST:event_jButton2ActionPerformed
    
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        
        if (filepath.isEmpty()) {
            JLabel label = new JLabel("Original foto belum di input!", (int) CENTER_ALIGNMENT);
            
            jScrollPane1.setViewportView(label);
        } else {
            try {
                String resultpath = counter + ".jpg";
                
                int algorithm = jComboBox1.getSelectedIndex();
                
                int[][] matrix = ImageReader.ReadImageAsGrayScale(filepath);
                
                int[][] new_matrix = null;
                
                Transformation t;
                EdgeDetection edge;
                
                switch(algorithm) {
                    case 0:
                        t = new LinearTransformation();
                        new_matrix = t.doTransform(matrix) ;
                        
                        break;
                    case 1:
                        t = new NineNTransformation();
                        new_matrix = t.doTransform(matrix) ;

                        break;
                    case 2:
                        t = new LookUpTableMaker();
                        new_matrix = t.doTransform(matrix);
                        
                        break;
                    
                    case 3:
                        t = new DifferenceFunction();
                        new_matrix = t.doTransform(matrix);
                        
                        break;
                    case 4:
                        t = new SimpleDifference();
                        new_matrix = t.doTransform(matrix);
                        
                        break;

                    case 5:
                        edge = new FreiChenEdgeDetection();
                        new_matrix = edge.detect(matrix);
                        
                        break;
                    case 6:
                        edge = new KirschEdgeDetection();
                        new_matrix = edge.detect(matrix);
                        
                        break;
                    case 7:
                        edge = new PrewittEdgeDetection();
                        new_matrix = edge.detect(matrix);
                        
                        break;
                    case 8:
                        edge = new RobertEdgeDetection();
                        new_matrix = edge.detect(matrix);
                        
                        break;
                    case 9:
                        edge = new SobelEdgeDetection();
                        new_matrix = edge.detect(matrix);
                        
                        break;
                    case 10:
                        edge = new FreiChen2EdgeDetection();
                        new_matrix = edge.detect(matrix);
                        
                        break;
                    case 11:
                        edge = new Prewitt2EdgeDetection();
                        new_matrix = edge.detect(matrix);
                        
                        break;
                    case 12:
                        edge = new Robert2EdgeDetection();
                        new_matrix = edge.detect(matrix);
                        
                        break;
                    case 13:
                        edge = new Sobel2EdgeDetection();
                        new_matrix = edge.detect(matrix);
                        
                        break;
                    case 14:
                        WetLeftHand wet = new WetLeftHand();
                        
                        int[][] matrix_blackandwhite    = wet.blackAndWhiteConverter(matrix);
                        
                        String[]    chain_codes = wet.doWetLeftHand(matrix_blackandwhite);
                        String[]    shapes      = new String[chain_codes.length];
                        
                        for (int i = 0; i < shapes.length; i++) {
                            shapes[i] = wet.guessObject(chain_codes[i]);
                        }
                        
                        String forLabel = "<html>Ditemukan " + chain_codes.length + " benda<br>";
                        
                        for(int i = 0; i < chain_codes.length; i++) {
                            forLabel += ("benda" + (i + 1) + " = " + shapes[i] + "<br>");
                        }
                        
                        forLabel += "</html>";
                        JLabel label = new JLabel(forLabel, (int) CENTER_ALIGNMENT);
                        
                        jScrollPane1.setViewportView(label);                        
                        break;
                    case 15 :
                        WetLeftHand wet2 = new WetLeftHand();
                        
                        int[][] preprocess    = wet2.blackAndWhiteConverter(matrix);
                        
                        String[]    chain_codes2 = wet2.doWetLeftHand(preprocess);
                        String[]    numbers      = new String[chain_codes2.length];
                        
                        for (int i = 0; i < numbers.length; i++) {
                            ChainCode temp = new ChainCode(0, 0, chain_codes2[i].substring(chain_codes2[i].indexOf("Y")));
                            numbers[i] = ChainCode.MatchWithModels(temp, models).getName();
                        }
                        
                        String forLabel2 = "<html>Ditemukan " + chain_codes2.length + " benda<br>";
                        
                        for(int i = 0; i < chain_codes2.length; i++) {
                            forLabel2 += ("Angka" + (i + 1) + " = " + numbers[i] + "<br>");
                        }
                        
                        forLabel2 += "</html>";
                        JLabel label2 = new JLabel(forLabel2, (int) CENTER_ALIGNMENT);
                        
                        jScrollPane1.setViewportView(label2);                        
                        break;
                    case 16 :
                            System.out.println("Check");
                            new_matrix = CheckNumber();
                        break;
                    case 17:
                        PredictNumberWithStatisticModel1(matrix);
                        break;
                    case 18:
                        matrix = ImageReader.ReadImageAsRGB(filepath);
                        FaceDetection faceDetection = new FaceDetection();
                        new_matrix = faceDetection.doSegementation(matrix);
                        break;
                    case 19 :
                        matrix = ImageReader.ReadImageAsRGB(filepath);
                        ScaleTranformation scaleTransform = new ScaleTranformation();
                        new_matrix = scaleTransform.doTransform(matrix, new int[] {61,52,187,243}, 
                                new int[]{61,30,187,10,61,243,187,250});
                        break;
                    default:
                        break;
                        
                }
                
                if (new_matrix != null) {
                    System.out.println("Sini");
                    BufferedImage new_img = ImageWriter.WriteImageRGB(new_matrix);
                    ImageWriter.WriteImage(new_img, resultpath);

                    ImageIcon   image = new ImageIcon(resultpath);
                    JLabel      label = new JLabel(image);

                    jScrollPane1.setViewportView(label);
                    jScrollPane1.setVisible(true);

                    counter++;
                }
                /*
                jScrollPane1.validate();
                jScrollPane1.revalidate();
                jScrollPane1.repaint();
                jScrollPane1.updateUI(); // */
                
                //System.out.println(algorithm);
            } catch (IOException ex) {
                Logger.getLogger(CobaGUI.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
    }//GEN-LAST:event_jButton1ActionPerformed

    public int[][] CheckNumber() {
        int[][] matrix = ImageReader.ReadImageAsGrayScale(filepath);
        
        //WetLeftHand wet = new WetLeftHand();
        
        /*int[][] binaryImage    = ImageHelper.convertToBinaryImage(matrix, true);
        
        ZhangSuen zhthining = new ZhangSuen();
        binaryImage = zhthining.doZhangSuenThinning(binaryImage);
        
        int[][] new_matrix_grayscale = ImageHelper.convertBinaryToGrayscaleImage(binaryImage, true);
        */
        ThinModel[] thins = ThinModel.generateThinModels(matrix);
        System.out.println("Thin Model Found : " + thins.length);
        System.out.println("Thin Model Ujung : " + thins[0].getUjungCount());
        /*int[][] matrix_blackandwhite    = wet.blackAndWhiteConverter(new_matrix_grayscale);

        String[]    chain_codes = wet.doWetLeftHand(matrix_blackandwhite);
        String[]    shapes      = new String[chain_codes.length];

        for (int i = 0; i < chain_codes.length; i++) {
            System.out.println(chain_codes[i]);
        }*/
        return matrix;
        /*
        String forLabel = "<html>Ditemukan " + chain_codes.length + " benda<br>";

        for(int i = 0; i < chain_codes.length; i++) {
            forLabel += ("benda" + (i + 1) + " = " + shapes[i] + "<br>");
        }

        forLabel += "</html>";
        JLabel label = new JLabel(forLabel, (int) CENTER_ALIGNMENT);

        jScrollPane1.setViewportView(label); */ 
    }
    
    public void PredictNumberWithStatisticModel1(int[][] matrix) {
        WetLeftHand wet2 = new WetLeftHand();
                        
        int[][] preprocess    = wet2.blackAndWhiteConverter(matrix);

        String[]    chain_codes2 = wet2.doWetLeftHand(preprocess);
        String[]    numbers      = new String[chain_codes2.length];

        for (int i = 0; i < numbers.length; i++) {
            ChainCode temp = new ChainCode(0, 0, chain_codes2[i].substring(chain_codes2[i].indexOf("Y")));
            numbers[i] = ChainCode.MatchWithModels(temp, statisticModel).getName();
        }

        String forLabel2 = "<html>Ditemukan " + chain_codes2.length + " benda<br>";

        for(int i = 0; i < chain_codes2.length; i++) {
            forLabel2 += ("Angka" + (i + 1) + " = " + numbers[i] + "<br>");
        }

                        forLabel2 += "</html>";
                        JLabel label2 = new JLabel(forLabel2, (int) CENTER_ALIGNMENT);
                        
                        jScrollPane1.setViewportView(label2);     
    }
    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jComboBox1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CobaGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new CobaGUI().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    // End of variables declaration//GEN-END:variables
    private String  filepath = "";
    private static  int counter = 0;
}
